import moment from 'moment'

export const storageCache = {
  setItem(key, data, age) {
    const payload = {
      data,
      createdAt: moment().unix(),
      expiresIn: moment().add(age, 'seconds').unix(),
    }
    localStorage.setItem(key, JSON.stringify(payload))
  },
  getItem(key) {
    let payload = localStorage.getItem(key)
    if (!payload) {
      // 无数据
      return null
    }

    payload = JSON.parse(payload)

    if (payload.expiresIn <= moment().unix()) {
      // 已过期
      return null
    }

    return payload.data
  },
  getItemTTL(key) {
    let payload = localStorage.getItem(key)
    if (!payload) {
      // 无数据
      return null
    }

    payload = JSON.parse(payload)

    return payload.expiresIn - moment().unix()
  },
  refreshItem(key) {
    let payload = localStorage.getItem(key)
    if (!payload) {
      // 无数据
      return
    }

    payload = JSON.parse(payload)

    if (!payload.createdAt || !payload.expiresIn) {
      // 不需要缓存的项
      return
    }

    if (payload.expiresIn <= moment().unix()) {
      // 已过期
      return
    }

    const age = payload.expiresIn - payload.createdAt

    this.setItem(key, payload.data, age)
  },
  removeItem(key) {
    localStorage.removeItem(key)
  },
}
